package top.codef.config;

import java.util.List;
import java.util.Map;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.hibernate.boot.model.TypeContributor;
import org.hibernate.cfg.AvailableSettings;
import org.hibernate.jpa.boot.spi.JpaSettings;
import org.hibernate.jpa.boot.spi.TypeContributorList;
import org.hibernate.type.format.jackson.JacksonJsonFormatMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.AutoConfigureBefore;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.autoconfigure.orm.jpa.HibernatePropertiesCustomizer;
import org.springframework.boot.autoconfigure.orm.jpa.JpaBaseConfiguration;
import org.springframework.context.annotation.Configuration;

import com.fasterxml.jackson.databind.ObjectMapper;

import top.codef.persist.contributors.MonetaryTypeContributor;

@SuppressWarnings("removal")
@Configuration
@AutoConfigureBefore({ JpaBaseConfiguration.class })
@ConditionalOnProperty(name = "mercury.money.persist.open-monetary-basic-type-persist", havingValue = "true")
public class MoneyHibernatePropertyCustomer implements HibernatePropertiesCustomizer {

	@Autowired
	private MonetaryTypeContributor monetaryTypeContributor;

	@Autowired
	private ObjectMapper objectMapper;

	private final Log logger = LogFactory.getLog(MoneyHibernatePropertyCustomer.class);

	@Override
	public void customize(Map<String, Object> hibernateProperties) {
		logger.debug("加入MonetaryTypeContributor配置");
		hibernateProperties.put(JpaSettings.TYPE_CONTRIBUTORS, new TypeContributorList() {
			@Override
			public List<TypeContributor> getTypeContributors() {
				return List.of(monetaryTypeContributor);
			}
		});
		logger.debug("加入sql中的json类型money相关配置");
		var mapper = new JacksonJsonFormatMapper(objectMapper);
		hibernateProperties.put(AvailableSettings.JSON_FORMAT_MAPPER, mapper);
	}
}
